package com.qiuling.iot.Exception.handler;

import com.qiuling.iot.Exception.BusinessException;
import com.qiuling.iot.Exception.code.BaseResponseCode;
import com.qiuling.iot.utils.DataResult;
import lombok.extern.slf4j.Slf4j;
import org.apache.shiro.authz.UnauthorizedException;
import org.springframework.validation.ObjectError;
import org.springframework.web.bind.MethodArgumentNotValidException;
import org.springframework.web.bind.annotation.ExceptionHandler;
import org.springframework.web.bind.annotation.RestControllerAdvice;

import java.util.List;

/**
 * @Author：zhangqiang
 * @Description：
 * @Date：Created in 13:40 2020/2/8
 * @Modified By：
 */
@RestControllerAdvice
@Slf4j
public class RestExceptionHandler {

    /**
     * 统一返回类
     * @param e
     * @return
     */
    @ExceptionHandler(value = Exception.class)
    public DataResult exception(Exception e) {
        log.error("Exception,{},{}", e.getLocalizedMessage(), e);
        return DataResult.getResult(BaseResponseCode.SYSTEM_ERROR);
    }

    /**
     * 业务异常
     * @param e
     * @return
     */
    @ExceptionHandler(value = BusinessException.class)
    public DataResult businessException(BusinessException e) {
        log.error("businessException,{},{}", e.getLocalizedMessage(), e);
        return DataResult.getResult(e.getCode(), e.getDefaultMessage());
    }

    /**
     * 框架异常
     * @param e
     * @param <T>
     * @return
     */
    @ExceptionHandler(MethodArgumentNotValidException.class)
    <T> DataResult<T> methodArgumentNotValidExceptionHandler(MethodArgumentNotValidException e) {

        log.error("methodArgumentNotValidExceptionHandler bindingResult.allErrors():{},exception:{}",
                e.getBindingResult().getAllErrors(), e);
        List<ObjectError> errors = e.getBindingResult().getAllErrors();
        return createValidExceptionResp(errors);
    }

    /**
     * 参数效验
     *
     * @param errors
     * @param <T>
     * @return
     */
    private <T> DataResult<T> createValidExceptionResp(List<ObjectError> errors) {
        String[] msgs = new String[errors.size()];
        int i = 0;
        for (ObjectError error : errors) {
            msgs[i] = error.getDefaultMessage();
            log.info("msg={}", msgs[i]);
            i++;
        }
        return DataResult.getResult(BaseResponseCode.METHOD_IDENTITY_ERROR.getCode(), msgs[0]);
    }

    /**
     * 无权限
     *
     * @param e
     * @return
     */
    @ExceptionHandler(UnauthorizedException.class)
    public DataResult unauthorizedException(UnauthorizedException e) {
        log.error("UnauthorizedException,{},{}", e.getLocalizedMessage(), e);
        return DataResult.getResult(BaseResponseCode.NOT_PERMISSION);
    }

}
